package org.wheel.plugins.toolkit.sql.rule.plugin;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.JdbcNamedParameter;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.wheel.plugins.toolkit.sql.helper.ColumnRef;
import org.wheel.plugins.toolkit.sql.plugin.RuleContext;
import org.wheel.plugins.toolkit.sql.plugin.RuleDataHolder;
import org.wheel.plugins.toolkit.sql.plugin.RulePlugin;

/**
 * 租户隔离规则 – 自动 WHERE tenant_id = :tenantId
 */
public class TenantRule implements RulePlugin {

    @Override
    public String name() {
        return "tenant";
    }

    @Override
    public void apply(PlainSelect select, RuleContext ctx) {
//        Long tenantId = ctx.getTenantId(); // 从上下文取

        if(!RuleDataHolder.containsKey(this.name())){
            return;
        }
        Pair<ColumnRef, Long> dataPair = (Pair<ColumnRef, Long>) RuleDataHolder.get(this.name());

        String key = StrUtil.toCamelCase(dataPair.getKey().getColumn());

        EqualsTo eq = new EqualsTo();
        eq.setLeftExpression(new Column(dataPair.getKey().withoutAlias().getSql()));
        eq.setRightExpression(new JdbcNamedParameter(key));
        // 追加到 WHERE
        Expression where = select.getWhere();
        if (where != null) {
            select.setWhere(new AndExpression(where, eq));
        } else {
            select.setWhere(eq);
        }
        ctx.addParam(key, dataPair.getValue());
    }
}